package singleton;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;

class SingletonDataSource {

    private static DataSource dataSource = null;

    public static DataSource getDataSource() {
        /**
         * 线程不安全
         */
//        if (dataSource == null) {
//            synchronized (SingletonDataSource.class) {
//                if (dataSource == null) {
//                    dataSource = new MysqlDataSource();
//                    ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
//                    ((MysqlDataSource)dataSource).setUser("root");
//                    ((MysqlDataSource)dataSource).setPassword("zzl666666");
//                }
//            }
//        }
//        return dataSource;

        /**
         * 线程安全
         */
        if (dataSource == null) {
            synchronized (SingletonDataSource.class) {
                if (dataSource == null) {
                    MysqlDataSource ds = new MysqlDataSource();
                    ds.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
                    ds.setUser("root");
                    ds.setPassword("zzl666666");
                    dataSource = ds;
                }
            }
        }
        return dataSource;
    }
}

public class demo4 {
    public static void main(String[] args) {
        DataSource ds1 = SingletonDataSource.getDataSource();
        DataSource ds2 = SingletonDataSource.getDataSource();
        System.out.println(ds1 == ds2);
    }

}
